<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>myCall</title>
</head>
<body>
<script>
    Function.prototype.myCall = function (obj, ...arg) {
        const self = this
        obj.execFunc = self
        eval("obj.execFunc(" + arg.join(",") + ")")
        delete obj.execFunc
    }

    // 1. 默认值
    // 2. 避免 key 重复值
    // 3. 借助于 eval 传参

    Function.prototype.myCall2 = (function () {
        function getUniqueKey(context) {
            var uni_que_fn = "fn"
            while (context.hasOwnProperty(uni_que_fn)) {
                uni_que_fn += Math.random()
            }
            return uni_que_fn
        }

        return function (obj, ...arg) {
            const context = obj || window
            const self = this
            const fn = getUniqueKey(context)
            context[fn] = self
            eval("context[" + fn + "](" + arg.join(",") + ")")
            delete context[fn]
        }
    })()

    const obj = {name: "obj.name"}
    var name = "window.name"

    function show() {
        console.log(this.name)
    }

    console.log("++++++++++++++++++")
    show()
    console.log("++++++++++++++++++")
    show.call(obj);
    console.log("++++++++++++++++++")
    show.myCall(obj);
    console.log("++++++++++++++++++")
    show.myCall2(obj);
    show.myCall2();
    console.log("++++++++++++++++++")

</script>
</body>
</html>
